var f0 = 'f';
var w0 = 'w0';
var w1 = 'w1';
var w2 = 'w2';
var w3 = 'w2';
var h0 = 'h0';
var h1 = 'h1';
var h2 = 'h2';
var e0 = 'e0';
var e1 = 'e1';
var e2 = 'e2';
var e3 = 'e3';

var blocks = {
	wall: [w0, w1, w2, w3, h0, h1, h2],
	walkable: [f0],
	explodable: [e0, e1, e2, e3]
};

head.js("js/maps/map_001.js");

/**
 * Initializes variables in main.js file
 */
function loadingReady() {
	var map = OurGame.mapFiles[OurGame.mapFiles.length - 1];
	if (map) {
		level.name = map.name;
		level.spawnPos = map.spawnPos;

        for (var i = 0; i < OurGame.players.length; i++){
            console.log("id " +  OurGame.players[i].id);
            OurGame.players[i].setPos(level.spawnPos.x[i], level.spawnPos.y[i]);
        }

		level.map = rows2cols(map.map);
	}
	OurGame.mapLoaded = true;
    OurGame.booleanMap = mapToBoolean();

}

function mapToBoolean() {
    var booleanMap = [];
    for (var i = 0; i < level.map.length; i++){
        if(!booleanMap[i]){booleanMap[i] = [];}
        for (var j = 0; j < level.map[0].length; j++){
            if (level.map[i][j].charAt(0) == "f"){
                booleanMap[i][j] = 0;
            }else{
                booleanMap[i][j] = 1;
            }
        }
    }
    return booleanMap;
}


/**
 * This is a transpose function. Changes lines to columns and contrary
 *
 * @param map array [[a1, a2, ...], [a1, a2, ...], ...]
 * @return array [[a1, b1, ...], [a2, b2, ...], ...]
 */
function rows2cols(map) {
	var r = [];
	var t;
	for (var i = 0, iLen = map.length; i < iLen; i ++) {
		t = map[i];
		for (var j = 0, jLen = t.length; j < jLen; j ++) {
			if (!r[j]) {
				r[j] = [];
			}
			r[j][i] = t[j];
		}
	}
	return r;
}

function isExplodable(pos) {
	try {
		if (blocks.explodable.indexOf(level.map[pos.x][pos.y]) >= 0) {
			return true;
		}
		else {
			return false;
		}
	}
	catch (e) {
		return false;
	}
}

function isWall(pos) {
	try {
		if (blocks.wall.indexOf(level.map[pos.x][pos.y]) >= 0) {
			return true;
		}
		else {
			return false;
		}
	}
	catch (e) {
		return false;
	}
}

function isWalkable(pos) {
	try {
		if (blocks.walkable.indexOf(level.map[pos.x][pos.y]) >= 0) {
			return true;
		}
		else {
			return false;
		}
	}
	catch (e) {
		return false;
	}
}

/**
 * Replaces given blocks with random walkable block
 * 
 * @param blocksToExplode [{x, y}]
 */
function explodeBlocks(blocksToExplode) {
    var randomInt;
    for (var i = 0; i < blocksToExplode.length; i++) {
        randomInt = Math.floor(Math.random() * blocks.walkable.length);
        level.map[blocksToExplode[i]['x']][blocksToExplode[i]['y']] = blocks.walkable[randomInt];
    }
}